<?php
namespace app\index\controller;
use app\extra\lib\ImgCut;
use app\extra\lib\MP3File;
use think\Controller;
use app\index\model\Url;
use think\Db;
use think\Session;

class Index extends Controller
{

    public function index()
    {
        return $this->fetch();
    }

    public function getLoveList()
    {
        $lovelist=null;

        if(Session::has('uid') && Session::has('lovelist'))
        {
            $sLoveList=Session::get('lovelist');
            $lovelist=explode(' ',$sLoveList);
            foreach ($lovelist as $l)
            {
                $l=trim($l,' ');
            }
            if($lovelist[count($lovelist)-1]=='')
                array_splice($lovelist,count($lovelist)-1,1);
        }
        if($lovelist!=null)
        return $lovelist;
        else
            return array(0);
    }

    public function getLoveListDetail()
    {
        $array=$this->getLoveList();
        $result=\db('musics')->field('m.mid,m.mname,m.poster,s.sname')->alias('m')->join('singers s','s.sid=m.sid')->where('mid','in',$array)->select();
        echo json_encode($result);
        die();
    }

    public function createPlayList($pname)
    {
        if(!Session::has('uid'))
        {
            echo json_encode(['status'=>0]);
            die();
        }

        try{
            \db('playlist')->insert(['pname'=>$pname,'uid'=>Session::get('uid')]);
            echo json_encode(['status'=>1]);
            die();
        }
        catch (\mysqli_sql_exception $exception){
            echo json_encode(['status'=>2]);
        }
    }



    public function add()
    {
        $result_type=\db('musictype')->select();
        if($result_type)
            $this->assign('types',$result_type);
        return $this->fetch();
    }

    public function update()
    {
        $s=explode('-',$_FILES['file_mp3']['name']);
        $sname=trim($s[0],' ');
        $mname=trim($s[1],' ');
        $mname=explode('.',$mname);
        $name_img='123.jpg';
        $name_mp3='123.mp3';
        $sid=1;
        if(request()->file('file_img'))
        {
            $file=request()->file('file_img');
            $info_img=$file->rule('uniqid')->validate(['ext'=>'jpg,png'])->move(Url::ImgLocal());
            if($info_img)
            {
                $name_img=$info_img->getFilename();
            }
            else
            {
                var_dump($file->getError());
            }
            $name_img=$info_img->getFilename();
            $imgCut=new ImgCut(Url::ImgUrl().$name_img,$name_img);
            $imgCut->CutALL();
        }
        if(request()->file('file_mp3'))
        {
            $info_mp3=request()->file('file_mp3')->rule('uniqid')->validate(['ext'=>'mp3'])->move(Url::MP3Local());
            $name_mp3=$info_mp3->getFilename();
        }
        $result_singer_s=\db('singers')->where('sname',$sname)->find();
        if($result_singer_s)
            $sid=$result_singer_s['sid'];
        else
            $sid=\db('singers')->insertGetId(['sname'=>$sname]);
        $mp3=new MP3File(Url::MP3Local().$name_mp3);
        $a = $mp3->getDurationEstimate();
        $b = $mp3->getDuration();
        $duration = $mp3::formatTime($b);
        $string_duration='';
        if($duration['hours'])
        {
            if($duration['hours']>=10)
                $string_duration=$string_duration.$duration['hours'].':';
            else
                $string_duration=$string_duration.'0'.$duration['hours'].':';
        }
        if($duration['minutes'])
        {
            if($duration['minutes']>=10)
                $string_duration=$string_duration.$duration['minutes'].':';
            else
                $string_duration=$string_duration.'0'.$duration['minutes'].':';
        }
        else
        {
            $string_duration=$string_duration.'00:';
        }
        if($duration['seconds']>=10)
            $string_duration=$string_duration.$duration['seconds'];
        else
            $string_duration=$string_duration.'0'.$duration['seconds'];
        $song=['mname'=>$mname[0],'sid'=>$sid,'tid'=>input('post.tid'),'file'=>$name_mp3,'poster'=>$name_img,'duration'=>$string_duration];
        $result=\db('musics')->insert($song);
        if($result)
            $this->success('添加成功');
      die();
    }

    public function getPlayList()
    {
        $result=db('playlist')->where('uid',Session::get('uid'))->select();
        $html='';
        foreach($result as $item)
        {
            $html=$html.'<li class="dd-item">                    
                                    <div class="dd-handle">
                                        '.$item['pname'].'
                                    <span class="pull-right"><a href="javascript:;" data-pid="'.$item['pid'].'" onclick="deletePlayList(this,1)"><i class="fa fa-times fa-fw"></i></a></span>
                                    </div>
                                    <ol class="dd-list">
                                        '.$this->getPlayListDetail($item['pid']).'
                                    </ol>
                                </li>';
        }
        return $html;
    }

    private function getPlayListDetail($pid)
    {
        $result=\db('plays')->field('p.mid,m.mname')->where('p.pid',$pid)->alias('p')->join('musics m','m.mid=p.pid')->select();
        $html='';
        foreach ($result as $item) {
            $html=$html.'<li class="dd-item">
                                            <div class="dd-handle">
                                                '.$item['mname'].'
                                            <span class="pull-right"><a href="javascript:;" data-mid="'.$item['mid'].'" data-pid="'.$pid.'" onclick="deletePlayList(this,0)"><i class="fa fa-times fa-fw"></i></a></span>
                                            </div>
                                        </li>';
        }
        return $html;
    }

    public function deletePlayList()
    {
        $pid=input('pid');
        $mid=0;
        if(input('?mid'))
            $mid=input('mid');
        $type=input('type');
        try{
            if($type==0)
            {
                \db('plays')->where('pid',$pid)->where('mid',$mid)->delete();
            }
            else
            {
                \db('plays')->where('pid',$pid)->delete();
                \db('playlist')->delete($pid);
            }
            echo json_encode(['status'=>1]);
            die();
        }
        catch (\mysqli_sql_exception $exception)
        {
            echo json_encode(['status'=>0]);
            die();
        }

    }

    public function getPersonInfo()
    {
        $uid=Session::get('uid');
        $user=\db('users')->find($uid);

        echo '<section class="hbox stretch">
                <aside class="aside-lg bg-light lter b-r">
                  <section class="vbox">
                    <section class="scrollable">
                      <div class="wrapper">
                            <div class="text-right m-b m-t">
                            <a href="javascript:;" onclick="showEditModal()"><i class="fa fa-align-left"></i>  修改信息 </a>    
                            </div>
                        <div class="text-center m-b m-t">
                          <a href="#" class="thumb-lg">
                            <img src="'.Url::HeadUrl().$user['hpic'].'" class="img-circle">
                          </a>
                          <div>
                            <div class="h3 m-t-xs m-b-xs">'.$user['nickname'].'</div>
                          </div>                
                        </div>
                        <div>
                          <strong class="text-uc text-xs text-muted text-center">about me</strong>
                          <div class="line"></div>
                            <p>'.$user['info'].'</p>
                        </div>
                      </div>
                    </section>
                  </section>
                </aside>
                <aside class="bg-white">
                  <section class="vbox">
                    <h4>歌单详情</h4>
                    <div id="Person_PlayList" class="container">
                        <div class="dd">
                              <ol class="dd-list">
                                '.$this->getPlayList().'
                              </ol>
                        </div>
                        
                    </div>
                    
                  </section>
                </aside>
              </section>';
        die();
    }

    public function getCon_Discover()
    {
        $lovelist=$this->getLoveList();

        $cout=\db('musics')->count();
        $min=1;
        $con_discover='';
        $numA[0]=0;
        for($i=0;$i<12;$i++)
        {
            $num=0;
            do{
                $num=rand($min,$min+$cout-1);
            }while(in_array($num,$numA));
            $numA[$i+1]=$num;
            $result=db('musics')->where('mid',$num)->alias('m')->join('singers s','m.sid=s.sid')->find();
            $con_discover=$con_discover.'<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
                                        <div class="item">
                                            <div class="pos-rlt">
                                                <div class="bottom">
                                                    <span class="badge bg-info m-l-sm m-b-sm">'.$result['duration'].'</span>
                                                </div>
                                                <div class="item-overlay opacity r r-2x bg-black">
                                                    <div class="center text-center m-t-n">
                                                        <a onclick="addList_play('.$result['mid'].')"><i class="icon-control-play i-2x"></i></a>
                                                    </div>
                                                    <div class="bottom padder m-b-sm">';
            if(in_array($result['mid'],$lovelist))
            {
                $con_discover=$con_discover. '<a href="javascript:;" class="pushLoveList pull-right active" data-mid="'.$result['mid'].'" >
                                                            <i class="fa fa-heart text-active text-danger"></i>
                                                            <i class="fa fa-heart-o text"></i>
                                                        </a>';
            }
            else
            {
                $con_discover=$con_discover. '<a href="javascript:;" class="pushLoveList pull-right" data-mid="'.$result['mid'].'" >
                                                            <i class="fa fa-heart text-active text-danger"></i>
                                                            <i class="fa fa-heart-o text"></i>
                                                        </a>';
            }
            $con_discover=$con_discover. '    <a href="javascript:;" data-mid="'.$result['mid'].'" data-mname="'.$result['mname'].'"  data-sname="'.$result['sname'].'"  onclick="addPL(this)">
                                                            <i class="fa fa-plus-circle text"></i>  
                                                        </a>
                                                    </div>
                                                </div>
                                                <a href="#"><img src="'.Url::ImgUrl_300_450().$result['poster'].'" alt="" class="r r-2x img-full"></a>
                                            </div>
                                            <div class="padder-v">
                                                <a href="#" class="text-ellipsis" onclick="showMusic('.$result['mid'].')">'.$result['mname'].'</a>
                                                <a href="#" onclick="showSinger('.$result['sid'].')"  class="text-ellipsis text-xs text-muted">'.$result['sname'].'</a>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="clearfix visible-xs"></div>';
        }
        return $con_discover;
    }

    public function getCon_Rank()
    {
        $result=\db('musics')->alias('m')->join('singers s','m.sid=s.sid')->field('mid,mname,poster,sname')->order('hittimes desc')->limit(10)->select();
        $con_rank='';
        for($i=0;$i<10;$i++)
        {
            $con_rank=$con_rank.'<a onclick="addList_play('.$result[$i]['mid'].')" class="list-group-item clearfix">
                                                <span class="pull-right h2 text-muted m-l">'.($i+1).'</span>
                                                <span class="pull-left thumb-sm avatar m-r">
															<img src="'.Url::ImgUrl_128_128().$result[$i]['poster'].'" alt="...">
                          								</span>
                                                <span class="clear">
                           								<span>'.$result[$i]['mname'].'</span>
														<small class="text-muted clear text-ellipsis">by '.$result[$i]['sname'].'</small>
														</span>
                                            </a>';

        }
        return $con_rank;
    }

    public function getSlidePlayList()
    {
        if(Session::has('uid'))
        {
            $uid=Session::get('uid');
            $result=\db('playlist')->where('uid',$uid)->field('pid,pname')->select();
            if($result)
                echo json_encode(['status'=>1,'info'=>$result]);
            else
                echo json_encode(['status'=>1,'info'=>null]);
            die();
        }
        echo json_encode(['status'=>0]);
        die();
    }

    public function getCon_New()
    {
        $result=\db('musics')->alias('m')->join('singers s','m.sid=s.sid')->order('mid desc')->limit(8)->select();
        $lovelist=$this->getLoveList();
        $con_new='';
        for($i=0;$i<8;$i++)
        {
            $con_new=$con_new.'<div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
                                                <div class="item">
                                                    <div class="pos-rlt">
                                                        <div class="item-overlay opacity r r-2x bg-black">
                                                            <div class="center text-center m-t-n">
                                                                <a onclick="addList_play('.$result[$i]['mid'].')"><i class="fa fa-play-circle i-2x"></i></a>
                                                            </div>
                                                            <div class="bottom padder m-b-sm">';
            if(in_array($result[$i]['mid'],$lovelist))
            {
                $con_new=$con_new.'<a href="javascript:;" class="pushLoveList pull-right active" data-mid="'.$result[$i]['mid'].'" >
                                                            <i class="fa fa-heart text-active text-danger"></i>
                                                            <i class="fa fa-heart-o text"></i>
                                                        </a>';
            }
            else
            {
                $con_new=$con_new.'<a href="javascript:;" class="pushLoveList pull-right" data-mid="'.$result[$i]['mid'].'" >
                                                            <i class="fa fa-heart text-active text-danger"></i>
                                                            <i class="fa fa-heart-o text"></i>
                                                        </a>';
            }
            $con_new=$con_new. '    <a href="javascript:;" data-mid="'.$result[$i]['mid'].'" data-mname="'.$result[$i]['mname'].'"  data-sname="'.$result[$i]['sname'].'"  onclick="addPL(this)">
                                                            <i class="fa fa-plus-circle text"></i>  
                                                        </a>
                                                    </div>
                                                        </div>
                                                        <a href="#"><img src="'.Url::ImgUrl_128_128().$result[$i]['poster'].'" alt=""
                                                                         class="r r-2x img-full"></a>
                                                    </div>
                                                    <div class="padder-v">
                                                        <a href="#" class="text-ellipsis" onclick="showMusic('.$result[$i]['mid'].')">'.$result[$i]['mname'].'</a>
                                                        <a href="#" onclick="showSinger('.$result[$i]['sid'].')"  class="text-ellipsis text-xs text-muted">'.$result[$i]['sname'].'</a>
                                                    </div>
                                                </div>
                                            </div>';
        }
        return $con_new;
    }


    public function getContent()
    {
        echo '<section class="scrollable padder-lg w-f-md" id="bjax-target">
                                <a href="#" class="pull-right text-muted m-t-lg" data-toggle="class:fa-spin">
                                <i onclick="refresh()" class="icon-refresh i-lg  inline" id="refresh"></i></a>
                                <h2 class="font-thin m-b">发现 <span class="musicbar animate inline m-l-sm"
                                                                   style="width:20px;height:20px">
                    <span class="bar1 a1 bg-primary lter"></span>
                    <span class="bar2 a2 bg-info lt"></span>
                    <span class="bar3 a3 bg-success"></span>
                    <span class="bar4 a4 bg-warning dk"></span>
                    <span class="bar5 a5 bg-danger dker"></span>
                  </span></h2>
                                <div class="row row-sm">
                                    <!--一个格子-->
                                    '.$this->getCon_Discover().'
                                    <!--一个格子结束-->
                                </div>
                                <div class="row">
                                    <div class="col-md-7">
                                        <h3 class="font-thin">新歌</h3>
                                        <div class="row row-sm">
                                        '.$this->getCon_New().'
                                        </div>
                                    </div>
                                    <div class="col-md-5">
                                        <h3 class="font-thin">排行榜 </h3>
                                        <div class="list-group bg-white list-group-lg no-bg auto">
                                            <!--一个格子-->
                                            '.$this->getCon_Rank().'
                                            <!--一个格子结束-->
                                        </div>
                                    </div>
                                </div>
                            </section>';
        die();
    }

    public function getMusicByMid($mid)
    {
        $result=\db('musics')->where('mid',$mid)->alias('m')->join('singers s','m.sid=s.sid')->find();
        if($result)
        {
            \db('musics')->where('mid',$mid)->setInc('hittimes');
            echo json_encode($result);
        }
        die();
    }

    public function setLoveList($mid)
    {
        if(!Session::has('uid'))
        {
            echo json_encode(['state'=>2]);
            die();
        }
        $lovelist=$this->getLoveList();
            $flag=true;
            $key=array_search($mid,$lovelist);
            if($key!=false)
            {
                $flag=false;
                array_splice($lovelist,$key,1);
            }
            else
            {
                $flag=true;
                $lovelist[count($lovelist)]=$mid;
            }
            sort($lovelist);
            $lovelist=array_unique($lovelist);
            $sLovelist=implode(' ',$lovelist);
            Session::set('lovelist',$sLovelist);
            $aLovelist=['lovelist'=>$sLovelist];
            $result=\db('users')->where('uid',Session::get('uid'))->update($aLovelist);
            if($result)
                echo json_encode(['state'=>1,'love'=>$flag]);
            else
                echo json_encode(['state'=>0]);
            die();
    }

}
